//webpack 4
const path = require('path')
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const webpack = require('webpack');
const HTMLPlugin = require('html-webpack-plugin'); //html-webpack-plugin
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
//判断环境变量，是否是开发环境
const isDev = process.env.NODE_ENV === 'development';

const config = {
  target: 'web', //webpack 编译目标
  //申明程序入口
  entry: path.join(__dirname, 'src/index.js'),
  //程序输出目标
  output: {
    filename: 'bundle.js',
    path: path.join(__dirname, 'dist')
  },
  plugins: [
    new VueLoaderPlugin(),
    //判断环境, 这里定义好，js代码中可以引用到
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: isDev ? '"development"' : '"production"'
      }
    }),
    new HTMLPlugin(), //html-webpack-plugin
  ],
  module: {
    rules: [{
        test: /\.vue$/, //检测文件类型，以 vue结尾文件
        loader: 'vue-loader'
      },
      { //babel-loader 处理 jsx 文件
        test: /\.jsx$/,
        loader: 'babel-loader'
      },
      {
        test: /\.(gif|jpg|jpeg|png|svg)/,
        use: [{
          loader: 'url-loader',
          options: { //用对象方式，可以指定参数
            limit: 1024, //图片小于此大小，直接base64转字符串，嵌在页面中，减少http请求
            name: '[name]-aaa.[ext]' //文件名.扩展名
          }
        }]
      }
    ]
  }
};

if (isDev) {
  //开发时的 css 处理配置
  config.module.rules.push({
    test: /\.styl(us)?$/,
    use: ['style-loader', 'css-loader',
      {
        loader: 'postcss-loader',
        options: {
          sourceMap: true
        }
      },
      'stylus-loader'
    ]
  });
  //F12 调试时，source看到的是编译前代码
  config.devtool = '#cheap-module-eval-source-map';
  //配置 dev server
  config.devServer = {
    port: 8000, //端口
    host: '127.0.0.1', //访问地址
    overlay: {
      errors: true, //网页上显示错误
    }
  };
  //webpack 热加载
  config.plugins.push(
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin()
  );
} else {
  // 正式环境打包
  config.optimization = {
    splitChunks: { // 打包 node_modules里的代码
      chunks: 'all'
    },
    runtimeChunk: true, // 打包 runtime 代码
  };
  config.plugins.push(
    new MiniCssExtractPlugin({
      filename: '[name].[contenthash:8].css',
      chunkFilename: '[id].css',
    }),
  );
  config.module.rules.push({
    test: /\.styl(us)?$/,
    use: [MiniCssExtractPlugin.loader, 'css-loader', 'stylus-loader']
  });
}

module.exports = config;